<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 示例</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        #messages {
            border: 1px solid #ccc;
            padding: 10px;
            height: 300px;
            overflow-y: scroll;
            margin-bottom: 10px;
        }
        #messageInput {
            width: calc(100% - 110px);
            padding: 5px;
        }
        #sendButton {
            padding: 5px 10px;
        }
    </style>
</head>
<body>
    <h1>WebSocket 示例</h1>
    <div id="messages"></div>
    <input type="text" id="messageInput" placeholder="输入消息...">
    <button id="sendButton">发送</button>

    <script>
        // WebSocket URL
        const wsUrl = 'ws://localhost:9002';
        let socket;

        function connectWebSocket() {
            socket = new WebSocket(wsUrl);

            socket.onopen = function(event) {
                appendMessage('已连接到服务器');
            };

            socket.onmessage = function(event) {
                appendMessage('收到消息: ' + event.data);
            };

            socket.onclose = function(event) {
                appendMessage('与服务器断开连接');
            };

            socket.onerror = function(error) {
                appendMessage('发生错误: ' + error.message);
            };
        }

        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            if (message) {
                socket.send(message);
                appendMessage('发送消息: ' + message);
                input.value = '';
            }
        }

        function appendMessage(message) {
            const messagesDiv = document.getElementById('messages');
            const messageElement = document.createElement('div');
            messageElement.textContent = message;
            messagesDiv.appendChild(messageElement);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        // 连接到WebSocket服务器
        connectWebSocket();

        // 发送按钮点击事件
        document.getElementById('sendButton').addEventListener('click', sendMessage);

        // 回车键发送消息
        document.getElementById('messageInput').addEventListener('keypress', function(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html>
